package com.ctrip.coverage.orm.ibaits.dao.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.executor.result.DefaultResultContext;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import com.ctrip.coverage.model.dto.SonarRuleDto;
import com.ctrip.coverage.model.dto.TfsFolderDto;
import com.ctrip.coverage.model.entity.SonarDataEntity;
import com.ctrip.coverage.orm.ibaits.dao.SonarDataDaoI;
import com.ctrip.coverage.utils.MapResultHandler;

@Repository("sonarDataDao")
public class SonarDataImpl extends SqlSessionDaoSupport implements SonarDataDaoI<SonarDataEntity> {

	@Resource
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		super.setSqlSessionFactory(sqlSessionFactory);
	}

	public Map<String, Float> findSonarData(Long snapId) throws DataAccessException {
		return getMap("SonarData.findSonarData", snapId, "name", "value");
	}

	public SonarDataEntity findSnap(TfsFolderDto tfsFolderDto) throws DataAccessException {
		return getSqlSession().selectOne("SonarData.findSnap", tfsFolderDto);

	}

	public Map<String, Float> getMap(String paramString, Long snapId, String mapKey, String mapValue) {

		ObjectFactory objectFactory = this.getSqlSession().getConfiguration()

		.getObjectFactory();

		List list = this.getSqlSession().selectList(paramString, snapId, RowBounds.DEFAULT);

		ObjectWrapperFactory objectWrapperFactory = this.getSqlSession()

		.getConfiguration().getObjectWrapperFactory();

		MapResultHandler mapResultHandler = new MapResultHandler(

		mapKey, mapValue, objectFactory, objectWrapperFactory);

		DefaultResultContext context = new DefaultResultContext();

		for (Iterator i$ = list.iterator(); i$.hasNext();) {

			Object o = i$.next();

			context.nextResultObject(o);

			mapResultHandler.handleResult(context);

		}

		Map selectedMap = mapResultHandler.getMappedResults();

		return selectedMap;

	}

	public List<SonarRuleDto> getSonarNetRule() {
		return getSqlSession().selectList("SonarData.getSonarNetRule");
	}

	public List<SonarRuleDto> getSonarLanguage() {
		return getSqlSession().selectList("SonarData.getSonarLanguage");
	}

	public String getSonarRuleNameById(Integer ruleId) {
		return getSqlSession().selectOne("SonarData.getSonarRuleNameById", ruleId);
	}
}
